<template>
  <div class="device-management">
    <div class="page-title">设备管理</div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="设备编码">
          <el-input v-model="searchForm.devCode" placeholder="请输入设备编码" clearable />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.devName" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item label="产线名称">
          <el-input v-model="searchForm.productionLine" placeholder="请输入产线名称" clearable />
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="searchForm.devStatus" placeholder="请选择设备状态" style="width: 150px" clearable>
            <el-option label="运行中" value="运行中" />
            <el-option label="停机" value="停机" />
            <el-option label="维修中" value="维修中" />
            <el-option label="报废" value="报废" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增设备
      </el-button>
      <el-button type="success" @click="handleImport">
        <el-icon><Upload /></el-icon> 导入设备
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-card>
      <el-table :data="deviceList" stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" v-if="false"/>
        <el-table-column prop="devCode" label="设备编码" />
        <el-table-column prop="devName" label="设备名称" />
        <el-table-column prop="productionLine" label="产线名称" />
        <el-table-column prop="devSpec" label="设备规格" />
        <el-table-column prop="devStatus" label="设备状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.devStatus)">
              {{ scope.row.devStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="devManager" label="设备管理人" />
        <el-table-column prop="buyTime" label="购入时间">
          <template #default="scope">
            {{ formatDate(scope.row.buyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 设备表单弹窗 -->
    <DeviceForm
      :visible="deviceFormVisible"
      @update:visible="deviceFormVisible = $event"
      :form-data="deviceFormData"
      @submit="handleFormSubmit"
      @close="handleFormClose" />

    <!-- 导入弹窗 -->
    <el-dialog
      title="导入设备数据"
      v-model="importVisible"
      width="500px"
      :before-close="handleImportClose">
      
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        action=""
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".xlsx,.xls"
        :limit="1">
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">
            请上传 Excel 文件（.xlsx 或 .xls 格式）
          </div>
        </template>
      </el-upload>

      <div class="import-template" style="margin-top: 15px;">
        <el-button type="text" @click="downloadTemplate">
          <el-icon><Download /></el-icon>
          下载导入模板
        </el-button>
      </div>

      <template #footer>
        <el-button @click="handleImportClose">取消</el-button>
        <el-button type="primary" @click="handleUpload" :loading="importLoading">导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Upload, Download } from '@element-plus/icons-vue'
import { request } from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

// 导入组件
import DeviceForm from './DeviceForm.vue'//'./Device/DeviceForm.vue'

// 响应式数据
const loading = ref(false)
const deviceList = ref([])
const deviceFormVisible = ref(false)
const importVisible = ref(false)
const importLoading = ref(false)
const uploadRef = ref()
const fileList = ref([])
const currentFile = ref(null)

// 搜索表单
const searchForm = reactive({
  devCode: '',
  devName: '',
  productionLine: '',
  devStatus: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 设备表单数据
const deviceFormData = reactive({
  id: '',
  devCode: '',
  devName: '',
  productionLine: '',
  buyTime: '',
  devSpec: '',
  devStatus: '运行中',
  devManager: ''
})

// 状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '运行中': 'success',
    '停机': 'warning',
    '维修中': 'danger',
    '报废': 'info'
  }
  return statusMap[status] || ''
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 加载设备数据
const loadDeviceData = async () => {
  loading.value = true
  try {
    const params = {
      filter: {
        pageIndex: pagination.current,
        pageSize: pagination.size,
        orderBy: "CREATETIME",
        isAscending: false
      },
      device: {
        ...searchForm
      }
    }
    
    // 调用后端API
    const response = await request.post('/Device/DevicePage', params)
    deviceList.value = response.data
    pagination.total = response.totalCount
  } catch (error) {
    ElMessage.error('加载设备数据失败')
    console.error('加载设备数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  loadDeviceData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.current = 1
  loadDeviceData()
}

// 新增设备
const handleAdd = () => {
  // 重置表单数据
  Object.keys(deviceFormData).forEach(key => {
    deviceFormData[key] = ''
  })
  deviceFormData.devStatus = '运行中'
  
  deviceFormVisible.value = true
}

// 编辑设备
const handleEdit = (row) => {
  // 填充表单数据
  Object.keys(deviceFormData).forEach(key => {
    if (row[key] !== undefined && row[key] !== null) {
      deviceFormData[key] = row[key]
    }
  })
  
  deviceFormVisible.value = true
}

// 删除设备
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除设备 "${row.devName}" 吗？`, '提示', {
      type: 'warning'
    })
    
    // 调用删除API
    await request.delete(`/Device/${row.id}`)
    ElMessage.success('删除成功')
    loadDeviceData()
    
  } catch (error) {
    console.log('删除取消或失败')
  }
}

// 表单提交处理
const handleFormSubmit = async (formData) => {
  try {
    if (formData.id) {
      // 编辑设备
      await request.post('/Device/Save', formData)
      ElMessage.success('更新成功')
    } else {
      // 新增设备
      await request.post('/Device/Save', formData)
      ElMessage.success('创建成功')
    }
    
    deviceFormVisible.value = false
    loadDeviceData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 表单关闭处理
const handleFormClose = () => {
  // 可以在这里添加关闭后的清理逻辑
}

// 导入设备
const handleImport = () => {
  importVisible.value = true
}

// 文件选择变化
const handleFileChange = (file) => {
  currentFile.value = file.raw
}
// 添加下载加载状态
const downloadLoading = ref(false)
// 下载模板
const downloadTemplate = async  () => {
downloadLoading.value = true
  try {
    // 创建模板数据
    const templateData = [
      {
        '设备编码': 'DEV001',
        '设备名称': '示例设备名称',
        '产线名称': '生产线A',
        '设备规格': '标准规格',
        '设备状态': '运行中',
        '设备管理人': '张三',
        '购入时间': '2023-01-01'
      }
    ]

    // 创建工作簿
    const wb = XLSX.utils.book_new()
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(templateData)
    
    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 设备编码
      { wch: 20 }, // 设备名称
      { wch: 15 }, // 产线名称
      { wch: 15 }, // 设备规格
      { wch: 10 }, // 设备状态
      { wch: 15 }, // 设备管理人
      { wch: 12 }  // 购入时间
    ]
    ws['!cols'] = colWidths
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '设备导入模板')
    
    // 生成Excel文件并下载
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
    const blob = new Blob([wbout], { type: 'application/octet-stream' })
    saveAs(blob, `设备导入模板_${new Date().toISOString().split('T')[0]}.xlsx`)
    
    ElMessage.success('模板下载成功')
    
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('模板下载失败，请重试')
  } finally {
    downloadLoading.value = false
  }
}

/// 上传文件
const handleUpload = async () => {
  if (!currentFile.value) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  importLoading.value = true
  try {
    // 读取并解析Excel文件
    const devices = await readExcelFile(currentFile.value)
    
    if (!devices || devices.length === 0) {
      ElMessage.warning('文件内容为空或格式不正确')
      return
    }

    // 调用导入API，发送JSON数据
    const response = await request.post('/Device/ImportDevices', devices, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.success) {
      ElMessage.success('导入成功')
      importVisible.value = false
      fileList.value = []
      currentFile.value = null
      loadDeviceData() // 重新加载数据
    } else {
      ElMessage.error(response.message || '导入失败')
    }
  } catch (error) {
    ElMessage.error('导入失败: ' + (error.message || '未知错误'))
    console.error('导入失败:', error)
  } finally {
    importLoading.value = false
  }
}

// 读取Excel文件并解析为设备数据
const readExcelFile = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        debugger;
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        
        // 获取第一个工作表
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        
        // 将工作表转换为JSON
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        
        // 映射字段到Device对象
        const devices = jsonData.map(row => {
          // 根据Excel列名映射到Device属性
          const device = {
            devCode: row['设备编码'] || row['devCode'],
            devName: row['设备名称'] || row['devName'],
            productionLine: row['产线名称'] || row['productionLine'],
            devSpec: row['设备规格'] || row['devSpec'],
            devStatus: row['设备状态'] || row['devStatus'],
            devManager: row['设备管理人'] || row['devManager'],
            buyTime: formatExcelDate(row['购入时间'] || row['buyTime'])
          }
          return device
        }).filter(device => device.devCode && device.devName) // 过滤空数据
        
        resolve(devices)
      } catch (error) {
        reject(new Error('文件解析失败: ' + error.message))
      }
    }
    
    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }
    
    reader.readAsArrayBuffer(file)
  })
}

// 格式化Excel日期
const formatExcelDate = (excelDate) => {
  if (!excelDate) return null
  
  // 如果已经是Date对象
  if (excelDate instanceof Date) {
    return excelDate.toISOString()
  }
  
  // 如果是数字（Excel日期序列号）
  if (typeof excelDate === 'number') {
    const date = XLSX.SSF.parse_date_code(excelDate)
    return new Date(date.y, date.m - 1, date.d).toISOString()
  }
  
  // 如果是字符串，尝试解析
  if (typeof excelDate === 'string') {
    // 尝试多种日期格式
    const dateFormats = [
      'YYYY-MM-DD',
      'YYYY/MM/DD',
      'MM/DD/YYYY',
      'DD/MM/YYYY'
    ]
    
    for (const format of dateFormats) {
      const date = new Date(excelDate)
      if (!isNaN(date.getTime())) {
        return date.toISOString()
      }
    }
  }
  
  return null
}

// 关闭导入弹窗
const handleImportClose = () => {
  importVisible.value = false
  fileList.value = []
  currentFile.value = null
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadDeviceData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.current = page
  loadDeviceData()
}

// 页面加载时获取数据
onMounted(() => {
  loadDeviceData()
})
</script>

<style scoped>
.device-management {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.upload-demo {
  width: 100%;
}

.import-template {
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
}
</style>